package com.open.pokergames.conn.websocket;

import android.os.Handler;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.open.pokergames.NetConfig;
import com.open.pokergames.conn.bean.Message;
import com.open.pokergames.conn.bean.PersonMsg;
import com.open.pokergames.conn.bean.RoomMsg;
import com.open.pokergames.conn.bean.WsConstant;
import com.sinothk.android.utils.XUtils;

import org.greenrobot.eventbus.EventBus;

import java.net.URI;

public class MessageManager {

    String playerAcc = "";
    private static JWebSocketClient socketClient;

    private static MessageManager singObj;

    public static MessageManager obj() {
        if (null == singObj) {
            synchronized (MessageManager.class) {
                if (null == singObj) {
                    singObj = new MessageManager();
                }
            }
        }
        return singObj;
    }

    public void start(String account) throws InterruptedException {
        playerAcc = account;
        URI uri = URI.create("ws://" + NetConfig.SOCKET_URL + "socket/" + account);

        socketClient = new JWebSocketClient(uri) {
            @Override
            public void onMessage(String msg) {
                //message就是接收到的消息
                receiveMessage(msg);
            }
        };
        socketClient.connectBlocking();

        mHandler.postDelayed(heartBeatRunnable, HEART_BEAT_RATE);//开启心跳检测
    }

    private void receiveMessage(String msg) {
        try {
            Message message = JSON.parseObject(msg, Message.class);
            if (message == null) {
                Log.e("JWebSClientService", "onMessage 异常：" + msg);
                return;
            }

            if (WsConstant.MsgType.TYPE_PERSON == message.getType()) {
                PersonMsg personMsg = JSON.parseObject(message.getBody(), PersonMsg.class);
                EventBus.getDefault().post(personMsg);

            } else if (WsConstant.MsgType.TYPE_ROOM == message.getType()) {
                RoomMsg roomMsg = JSON.parseObject(message.getBody(), RoomMsg.class);
                EventBus.getDefault().post(roomMsg);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            Log.e("JWebSClientService", "收到：" + msg);
        }
    }

    public void startAuto() throws InterruptedException {
        URI uri = URI.create("ws://" + NetConfig.SOCKET_URL + "socket/" + playerAcc);

        socketClient = new JWebSocketClient(uri) {
            @Override
            public void onMessage(String msg) {
                //message就是接收到的消息
                receiveMessage(msg);
            }
        };
        socketClient.connectBlocking();
    }

    /**
     * 断开连接
     */
    public void close() {
        try {
            if (null != socketClient) {
                socketClient.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            socketClient = null;
        }
    }

    public boolean isOpen() {
        if (null != socketClient) {
            return socketClient.isOpen();
        }
        return false;
    }

    public void sendMsg(Object msg) {
        if (null == socketClient) {
            XUtils.toast().show("socketClient == null");
            try {
                startAuto();
                Log.e("JWebSClientService", "发出：startAuto重连");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return;
        }

        if (null == msg) {
            XUtils.toast().show("msg == null");
            return;
        }

        String message = JSON.toJSONString(msg);
        Log.e("JWebSClientService", "发出：" + message);
        if (socketClient.isOpen()) {
            socketClient.send(message);
        }
    }

    private static final long HEART_BEAT_RATE = 10 * 1000;//每隔10秒进行一次对长连接的心跳检测
    private Handler mHandler = new Handler();
    private Runnable heartBeatRunnable = new Runnable() {
        @Override
        public void run() {
//            Log.e(MessageManager.class.getSimpleName(), "每隔10秒进行一次对长连接的心跳检测");
            if (socketClient != null) {
                if (socketClient.isClosed()) {
                    reconnectWs();
                } else {
                    socketClient.send("");
//                    Log.e(MessageManager.class.getSimpleName(), "发出心跳空包数据");
                }
            } else {
                //如果client已为空，重新初始化websocket
                try {
                    startAuto();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //定时对长连接进行心跳检测
            mHandler.postDelayed(this, HEART_BEAT_RATE);
        }
    };

    /**
     * 开启重连
     */
    private void reconnectWs() {
        mHandler.removeCallbacks(heartBeatRunnable);
        new Thread() {
            @Override
            public void run() {
                try {
                    //重连
                    socketClient.reconnectBlocking();
                    Log.e(MessageManager.class.getSimpleName(), "开启重连");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
}
